#!/app/perl/5.8.7/bin/perl
use warnings;
use strict;
use POSIX qw/strftime/;
use Time::Local qw/timegm timegm_nocheck/;
use CGI;

my $time_start = "";
my $time_lunch = "";
my $time_end   = "";


my $jscript=<<EOT
var timerID = null;
var timerRunning = false;
var time_str = "";
var date_str = "";
function stopclock ()
{
    if(timerRunning)
	clearTimeout(timerID);
    timerRunning = false;
}
function showtime () {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    time_str = "" + ((hours < 10) ? "0" + hours : hours);
    time_str += ((minutes < 10) ? ":0" : ":") + minutes;
    date_str = "" + (now.getYear()+1900) + "-" +
	((now.getMonth()+1<10)?"0":"") + (now.getMonth()+1) + "-" +
	((now.getDate()<10)?"0":"") + now.getDate();
    document.time_form.current_date.value = date_str;
    document.time_form.current_time.value = time_str;
    timerID = setTimeout("showtime()",10000);
    timerRunning = true;
}
function startclock ()
{
    // Make sure the clock is stopped
	stopclock();
    showtime();
}
function set_start_now () {
    document.time_form.time_start.value = time_str;
}
function set_time_lunch () {
    document.time_form.time_lunch.value = document.time_form.menu_time_lunch.value;
}
function set_end_now () {
    document.time_form.time_end.value = time_str;
}
function text_time_change () {
    stopclock();
    var start_str = document.time_form.time_start.value;
    var lunch_str = document.time_form.time_start.value;
    start_str.replace(/:/, "");
    lunch_str.replace(/:/, "");
    var start_sec = start_str.substr(0,2) * 3600 + start_str.substr(3,2) * 60;
    var lunch_sec = 0;
    if (lunch_str.length == 4) {
	lunch_str.substr(0,2) * 3600 + lunch_str.substr(3,2) * 60;
    }
    var end_sec = start_sec + lunch_sec + 8 * 3600;
    //document.time_form.current_date.value = "" + (start_str.substr(0,2) * 3600) + "+" + (start_str.substr(3,2) * 60);
    var end_date = new Date();
    end_date.setTime(end_sec * 1000);
    document.time_form.current_date.value = end_date;
    var end_str = "" + ("" + (end_date.getHours() + 100)).substr(1,2) + ":" +
	("" + (end_date.getMinutes() + 100)).substr(1,2);
    document.time_form.time_end.value = end_str;
}
EOT
;

my $q = new CGI();

print $q->header();
print $q->start_html(-title=>"markldan's worktime-logging tool",
		     -script=>$jscript,
		     -onLoad=>"startclock()");

print $q->start_form(-name=>'time_form');
print "Current time : " .
    $q->textfield(-name=>"current_date",
		  -size=>20) .
    $q->textfield(-name=>"current_time",
		  -size=>5,
		  -maxlength=>5);



if (!$q->param()) {
    my $time_file = `cat time_2005.txt`;
    # First clean up formating.
    $time_file =~ s/^\s*//mg;  #Remove leading whitespaces
    $time_file =~ s/\#.*//g;  #Remove comments
    $time_file =~ s/\s*$//g;  #Remove trailing whitespaces
    $time_file =~ s/[ \t]+/ /g; #Remove repeated whitespaces

    my ($time_file_pre, $week, $time_file_rest) = $time_file =~ /(.*)^week (\d+)(.*?)\Z/msi; #This will find the last week in the file.
    my ($year) = $time_file_pre =~ /.*?^year (\d+)/msi; # This will get the first year in the file.
    my ($month) = $time_file =~ /.*^month (\d+)/msi; #This will get the last month in the file.
    my ($mday, $mday_rest) = $time_file =~ /.*^(\d+) (.*?)/msi; #This will get the last day in the file.
    print "<TABLE border=1>\n";
    print "<TR><TH>Week $week\n";
    print "<TR><TH>Date<TH>Start<TH>Lunch<TH>End<TH>Comment\n";
    
    #print "\nyear = $year, month = $month, week = $week, rest = $time_file_rest\n";
    foreach my $line (split(/\n/, $time_file_rest)) {
	next if $line =~ /^=/; #project lines will be handled in the future.
	if ($line =~ /^month (\d+)/) {
	    $month = $1;
	    next;
	}
	my ($mday, $time_start, $time_lunch, $time_end, $comment) = split(/\s/, $line, 5);
	next unless defined $mday;
	$time_start .= ""; # just to for sure make the string defined
	$time_lunch .= ""; # just to for sure make the string defined
	$time_end   .= ""; # just to for sure make the string defined
	$comment    .= ""; # just to for sure make the string defined
	my $epoc = timegm(0,0,0,$mday,$month-1,$year);
	print "<TR><TD>${year}-${month}-${mday}\n";
	print "    <TD>" . $q->textfield(-name=>"tf_time_start_$epoc", -value=>"$time_start", -size=>5) . "\n";
	print "    <TD>" . $q->textfield(-name=>"tf_time_lunch_$epoc", -value=>"$time_lunch", -size=>5) . "\n";
	print "    <TD>" . $q->textfield(-name=>"tf_time_end_$epoc", -value=>"$time_end", -size=>5) . "\n";
	print "    <TD>" . $q->textfield(-name=>"tf_comment_$epoc", -value=>"$comment", -size=>20) . "\n";
    }
    print "</TABLE>\n";
}
if (!$q->param()) {
    my $this_day = `cat this_day.txt`;
    my @this_day_l = split(/,/, $this_day);
    my $current_date = strftime("%Y-%m-%d", localtime);
    if ($this_day_l[0] eq $current_date) {
	if (scalar @this_day_l > 1) {
	    $time_start = $this_day_l[1];
	}
	elsif (scalar @this_day_l > 2) {
	    $time_lunch = $this_day_l[2];
	}
	elsif (scalar @this_day_l > 3) {
	    $time_end = $this_day_l[3];
	}
    }
    else {
	print "this is NOT the day('$this_day', '$this_day_l[0]')<BR>\n";
    }
}
print "<TABLE>\n";
print "<TR><TD>Start:\n";
print "    <TD>" . $q->textfield(-name=>'time_start', -size=>4, -value=>$time_start, -onChange=>'text_time_change()') . "\n";
print "    <TD>" . $q->button(-name=>"button_time_start", -value=>"Now", -onClick=>"set_start_now()") . "\n";
print "<TR><TD>Lunch:\n";
print "    <TD>" . $q->textfield(-name=>'time_lunch', -size=>4, -value=>$time_lunch) ."\n";
print "    <TD>" . $q->popup_menu(-name=>'menu_time_lunch',
				  -values=>['', '00:30', '00:45', '01:00', '01:15', '01:30'],
				  -default=>'',
				  -onChange=>'set_time_lunch()') . "\n";
print "<TR><TD>End:\n";
print "    <TD>" . $q->textfield(-name=>'time_end', -size=>4, -value=>$time_end) ."\n";
print "    <TD>" . $q->button(-name=>"button_time_end", -value=>"Now", -onClick=>"set_end_now()") . "\n";
print "<TR><TD>" . $q->submit(-name=>"button_time_save", -value=>"Save") . "\n";
print "    <TD>" . $q->submit(-name=>"button_time_commit", -value=>"Commit") . "\n";
print "</TABLE>\n";
print $q->end_form();

print $q->p;

if ($q->param("button_time_save")) {
    my $this_day_str = $q->param("current_date") . "," .
	$q->param("time_start") . "," .
	$q->param("time_lunch") . "," .
	$q->param("time_end") . "\n";
    my $str = `echo "$this_day_str" > this_day.txt`;
    print "Saved '$this_day_str' in this_day.txt: '$str'\n";
    print $q->p;
}

# if ($q->param("save_time")) {
#     open(FILE, ">>" , "time.txt");# or (print $q->h1("ERROR: Can't open file: $!") and return);
#     print FILE "tid = " . $q->param("current_time");
    
# }

